package priv.pront.code.national.acwing.search.dfs;

import java.util.Scanner;

/**
 * @Description:
 * @Author: pront
 * @Time:2023-05-27 22:07
 */
public class Acwing1117_单词接龙 {

    static Scanner sc = new Scanner(System.in);
    static int[][] g; //g[i][j]代表第i个字符串和第j个字符串的公共字符数，i字符串在前，j字符串在后
    static int[] used;
    static int n,res;
    static String[] word;
    public static void main(String[] args) {
        n =sc.nextInt();
        word = new String[n];
        g = new int[n][n];
        used = new int[n];
        for (int i = 0; i < n; i++) {
            word[i]=sc.next();
        }
        //求前缀与后缀相同数组长度  保存到g数组
        for (int i = 0; i < n; i++) {
            String a = word[i];
            for (int j = 0; j < n; j++) {
                String b = word[j];
                for (int k = 1; k <Math.min(a.length(),b.length()) ; k++) {
                    if (a.substring(a.length()-k,a.length()).equals(b.substring(0,k))){
                        g[i][j]=k; //找到第一个比较小的k即可
                        break;
                    }
                }
            }
        }
        char h = sc.next().charAt(0);
        for (int i = 0; i < n; i++) {
            if (word[i].charAt(0)==h){
                dfs(word[i],i);
            }
        }
        System.out.println(res);
    }

    private static void dfs(String s, int last) {
        res = Math.max(s.length(),res);
        used[last]++;
        for (int i = 0; i < n; i++) {
            if (g[last][i]!=0&&used[i]<2){
                int k =g[last][i];
                dfs(s+word[i].substring(k),i);
            }
        }
        used[last]--;

    }
}
